import axios from 'axios';
import {message} from 'antd';
import {config as mConfig} from '../config';
import mUtils from './utils';

export const baseurl = mConfig.serverUrl;
axios.defaults.baseURL = baseurl;
axios.defaults.timeout = 50000;


export const post = async (url, params, isShow = true) => {
    const token = mUtils.getToken();
    const result = await axios({
        url: url + '?token=' + token,
        method: "POST",
        headers: {contentType: 'application/json' },
        data: params,
    });
    if (result.status === 200) {
        if (mConfig.debug) {
            console.info(`请求开始 ${url} =================`);
            console.info('参数:', params);
            console.info('结果:', result.data);
            console.info(`请求结束 ${url} ^^^^^^^^^^^^^^^^^`);
        }
        const {state, showmsg, data} = result.data;
        if (state === 2 && isShow) {
            message.error(showmsg || data);
        } else if (state !== 1 && state !== 2) {
            let error = showmsg;
            if (data) {
                error = data;
            }
            message.error(`${error}`);
            mUtils.error(`${state} ${error}`);
        }
        return result.data;
    } else {
        message.error("请检查网络连接");
        return {state: -1};
    }
};

export const get = async (url, params, type) => {
    params.token = mUtils.getToken();
    const result = await axios.get(url, {params: params});
    const {state, showmsg} = result.data;
    if (type === 'code') {
        return result.data;
    } else if (state !== 1) {
        message.error(showmsg);
        window.loginOut();
        return result.data || {};
    } else {
        return result.data || {};
    }
};
export default axios;
